14. Process User
getProcUser()
8# Class ProcessParser - GetProcUser
The process user is retrieved from proc/[PID]/status
. From this file we can retrieve the UID, which is the ID of the process owner. To retrieve this ID, open a read stream on /etc/passwd
and search for "Uid:". The UID is the next token on that line.
Once we have the UID, we can look up the username from /etc/passwd
.
string ProcessParser::getProcUser(string pid)
{
string line;
string name = "Uid:";
string result ="";
ifstream stream = Util::getStream((Path::basePath() + pid + Path::statusPath()));
// Getting UID for user
while (std::getline(stream, line)) {
if (line.compare(0, name.size(),name) == 0) {
istringstream buf(line);
istream_iterator<string> beg(buf), end;
vector<string> values(beg, end);
result = values[1];
break;
}
}
stream = Util::getStream("/etc/passwd");
name =("x:" + result);
// Searching for name of the user with selected UID
while (std::getline(stream, line)) {
if (line.find(name) != std::string::npos) {
result = line.substr(0, line.find(":"));
return result;
}
}
return "";
}